<template>
  <TresGroup ref="birdRef" :position="[0, 1.5, -1]" :scale="1">
    <primitive :object="model.scene" />
  </TresGroup>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useGLTF } from "@tresjs/core"; // 保留 useGLTF 从 core 导入
import { useFrame } from "@tresjs/core"; // 从 cientos 导入 useFrame
import { gsap } from "gsap";

const props = defineProps({
  targetPosition: {
    type: Object,
    required: true,
    default: () => ({ x: 0, y: 0, z: 0 }),
  },
});

// 引用和状态
const birdRef = ref(null);
const { scene: model, animations } = useGLTF(
  "./model_assets/flying_synthwave_bird.glb"
);
let mixer = null;
let animationAction = null;

// 初始化动画
onMounted(() => {
  if (animations && animations.length > 0) {
    const targetAnimation = animations.find(
      (animation) => animation.name === "Armature.001|Scene|Scene"
    );

    if (targetAnimation) {
      mixer = new THREE.AnimationMixer(model);
      animationAction = mixer.clipAction(targetAnimation);
      animationAction.reset().fadeIn(0.5).play();

      // 使用 useFrame 更新动画
      useFrame((state) => {
        if (mixer) {
          mixer.update(state.clock.getDelta());
        }
      });
    }
  }
});

// 监听目标位置变化并旋转鸟
watch(
  () => props.targetPosition,
  () => {
    rotate();
  }
);

// 旋转函数
const rotate = () => {
  if (!birdRef.value) return;

  const { rotateAngle } = autoRotate(
    [props.targetPosition.x, props.targetPosition.z],
    [0, -1]
  );

  gsap.to(birdRef.value.rotation, {
    duration: 0.6,
    y: rotateAngle,
  });
};

// 自动计算旋转角度
const autoRotate = (targetPosi, objectPosi) => {
  let A = Math.atan(
    (targetPosi[0] - objectPosi[0]) / (targetPosi[1] - objectPosi[1])
  );
  if (props.targetPosition.z >= -1) A += Math.PI;
  return { rotateAngle: A };
};
</script>
